<?php

namespace app\admin\service;

use app\common\model\auth\Admin as AdminModel;
use app\common\model\auth\SystemRole;
use tmcore\base\BaseService;
use tmcore\exceptions\JwtException;
use tmcore\services\JwtTokenService;

/**
 * 管理员token服务类
 */
class AdminTokenService extends BaseService
{
    protected static string $token_type = 'admin';

    /**
     * 通过token获取管理员信息
     * @param $token
     * @return array|bool
     * @throws JwtException
     */
    public static function getAdminInfo($token)
    {
        $is_expire_extension = com_get_config('admin_token.is_expire_extension', 'core');
        $res = JwtTokenService::parseToken($token, $is_expire_extension);
        if($res) {
            if($res['type'] != self::$token_type) return self::setError('token类型有误');
            $admin = AdminModel::where(['id' => $res['id']])->append(['role_id'])->findOrEmpty();

            $roleName = '';
            $roleLists = SystemRole::column('name', 'id');
            if ($admin['root'] == 1) {
                $roleName = '系统管理员';
            } else {
                foreach ($admin['role_id'] as $roleId) {
                    $roleName .= $roleLists[$roleId] ?? '';
                    $roleName .= '/';
                }
                $roleName = trim($roleName, '/');
            }

            return [
                'id' => $admin->id,
                'root' => $admin->root,
                'name' => $admin->name,
                'account' => $admin->account,
                'role_name' => $roleName,
                'role_id' => $admin->role_id,
                'token' => $token,
                'channel' => $res['params']['channel']??'',
                'expire_time' => $res['params']['exp']??'',
            ];
        }
    }

    /**
     * 设置管理员token
     * @param int $id
     * @param integer $channel
     * @param boolean $multipointLogin
     * @return array|bool
     * @throws JwtException
     */
    public static function setToken($id, $channel, $multipointLogin)
    {
        $expire = com_get_config('admin_token.expire_duration', 'core');
        $res = JwtTokenService::createToken($id, self::$token_type, $expire, ['channel' => $channel], $multipointLogin);
        return ['token' => $res['token'], 'expire' => $expire];
    }

    /**
     * 清空 token
     * @param $id
     * @param $token
     * @return bool
     */
    public static function clearToken($id, $token = '')
    {
        return JwtTokenService::clearToken($id, self::$token_type, $token);
    }

}